package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.UserLoginService;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.common.AppJwtUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Map;

@Service
public class UserLoginServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements UserLoginService {
    @Autowired
    private AdUserMapper adUserMapper;
    private ResponseResult responseResult;

    @Override
    public ResponseResult login(AdUserDto dto) {
        // 参数校验
        if (StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR );
        }
        //数据库查询
        QueryWrapper<AdUser> adUserQueryWrapper = new QueryWrapper<>();
        adUserQueryWrapper.eq("name",dto.getName());
        AdUser one = getOne(adUserQueryWrapper);
        if (ObjectUtils.notEqual(one,null)){
            String password = one.getPassword();
            String password1 = dto.getPassword();
            //密文
            String s = DigestUtils.md5DigestAsHex((password1 + one.getSalt()).getBytes());
            if (s.equals(password)){
                //身分成token
                Map<String,Object> data= Maps.newHashMap();
                String token = AppJwtUtil.getToken(one.getId().longValue());
                data.put("token",token);
                data.put("user",one);
                return responseResult.okResult(data);
            }else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
    }
}
